package com.gwtplatform.samples.basic.server;

import com.google.inject.Inject;
import com.google.inject.Provider;

import com.guit.client.command.action.CommandException;
import com.guit.client.command.action.Handler;
import com.gwtplatform.samples.basic.shared.FieldVerifier;
import com.gwtplatform.samples.basic.shared.SendTextToServerAction;
import com.gwtplatform.samples.basic.shared.SendTextToServerResult;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

public class SendTextToServerHandler implements Handler<SendTextToServerAction, SendTextToServerResult> {

    private final Provider<HttpServletRequest> requestProvider;
    private final ServletContext servletContext;

    @Inject
    SendTextToServerHandler(ServletContext servletContext, Provider<HttpServletRequest> requestProvider) {
        this.servletContext = servletContext;
        this.requestProvider = requestProvider;
    }

    @Override
    public SendTextToServerResult handle(SendTextToServerAction action) throws CommandException {

        String input = action.getTextToServer();

        // Verify that the input is valid.
        if (!FieldVerifier.isValidName(input)) {
            // If the input is not valid, throw an IllegalArgumentException back to
            // the client.
            throw new CommandException("Name must be at least 4 characters long");
        }

        String serverInfo = servletContext.getServerInfo();
        String userAgent = requestProvider.get().getHeader("User-Agent");
        return new SendTextToServerResult("Hello, " + input + "!<br><br>I am running " + serverInfo
            + ".<br><br>It looks like you are using:<br>" + userAgent);
    }
}
